//
//  ConveyorBelt.m
//  MusicGame
//
//  Created by Matthew on 8/19/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ConveyorBelt.h"
#import "SimpleAudioEngine.h"
#import "CDAudioManager.h"
#import "CocosDenshion.h"
#import "Constants.h"

#define kGAMEOVERLOST NO
#define kGAMEOVERWON YES

@implementation ConveyorBelt

@synthesize gameOver;
@synthesize deadMarkers;
@synthesize startingMarkers;
@synthesize beltSpeed;
@synthesize beltInterval;

#pragma mark init/dealloc

- (id)init
{
    if( self = [super init] ) {
        
        self.isTouchEnabled = YES;
        
        [self setupMarkerAnimation];
        [self setGameOver:NO];
        
        rightPond = [[NSMutableArray array] retain];
        onBelt = [[NSMutableArray array] retain];
        
        [self setBeltSpeed:5];
        [self setBeltInterval:1];
        
        //    x, y, radius
        //    73,45,43; 
        //    398,45,43;
        //    48,123,43;
        //    433,123,43;
        //    48,206,43;
        //    433,206,43;
        //    73,282,43;
        //    398,282,43;
//        arrFramesPosition = [NSMutableArray array];bi
//        
//        [arrFramesPosition addObject:[NSValue valueWithCGPoint:ccp(73, 45)]];
//        [arrFramesPosition addObject:[NSValue valueWithCGPoint:ccp(398, 45)]];
//        [arrFramesPosition addObject:[NSValue valueWithCGPoint:ccp(48, 123)]];
//        [arrFramesPosition addObject:[NSValue valueWithCGPoint:ccp(433, 123)]];
//        [arrFramesPosition addObject:[NSValue valueWithCGPoint:ccp(48, 206)]];
//        [arrFramesPosition addObject:[NSValue valueWithCGPoint:ccp(433, 206)]];
//        [arrFramesPosition addObject:[NSValue valueWithCGPoint:ccp(73, 282)]];
//        [arrFramesPosition addObject:[NSValue valueWithCGPoint:ccp(398, 282)]];
    }
    
    return self;
}

- (void)dealloc
{
    [markerAnimation release];
    [rightPond release];
    [onBelt release];
    
    [super dealloc];
}

- (void)setupMarkerAnimation
{
    //[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"ducks_default.plist"];
    //CCSpriteBatchNode *spriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"ducks_default.png"];
    [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"marker.plist"];
    CCSpriteBatchNode *spriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"marker.png"];
    
    [self addChild:spriteSheet];
    
    NSMutableArray *markerFrames = [NSMutableArray array];
    //for(int i = 0; i <= 8; i++) {
       // [duckFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"duck%d.png", i]]];
    [markerFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"marker1.png"]]];
    //}
    //for(int i = 7; i >= 0; i--) {
     //   [duckFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"duck%d.png", i]]];
    //}
    
    CCAnimation* _animation = [CCAnimation animationWithFrames:markerFrames delay:0.1f];    
//    duckAnimation = [[CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:_animation restoreOriginalFrame:NO]] retain];
    markerAnimation = [[CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:_animation restoreOriginalFrame:NO]] retain];
    //duckAnimation = [[CCSprite spriteWithFile:@"marker.png"]]
}

-(void)registerObserver:(id)object
{
    [self addObserver:object forKeyPath:@"gameOver" options:NSKeyValueChangeSetting context:nil];
    [self addObserver:object forKeyPath:@"deadMarkers" options:NSKeyValueChangeSetting context:nil];
    [self addObserver:object forKeyPath:@"removeObserver" options:NSKeyValueChangeSetting context:nil];
}

-(void)unregisterObserver:(id)object
{
    [self removeObserver:object forKeyPath:@"gameOver"];
    [self removeObserver:object forKeyPath:@"deadMarkers"];
    [self removeObserver:object forKeyPath:@"removeObserver"];
}

#pragma mark Belt Control

- (void)start
{
    winSize = [[CCDirector sharedDirector] winSize];
    [self initializeMarkers];
    [self schedule:@selector(sendNextMarker:) interval:[self beltInterval]];
}

- (void)pause
{
    [self pauseSchedulerAndActions];
}

#pragma mark Set Up

- (void)initializeMarkers
{
    for( int i = 0; i < startingMarkers; i++ ) {
        Marker *marker = [Marker newMarker];
        [rightPond addObject:marker];
        [marker registerObserver:self];
        [marker setAnimation:[markerAnimation copy]];
        [self addChild:marker];
    }
    [self setDeadMarkers:0];
}

#pragma mark Game Logic

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if( [keyPath isEqualToString:@"hasBeenShot"] ) {
        [self setDeadMarkers:[self deadMarkers] + 1];
        
        // get rid of marker
        [onBelt removeObject:object];
        [object unregisterObserver:self];
        
        [markerStats setString:[NSString stringWithFormat:
            NSLocalizedString(@"%d dead %d alive", @"Marker Statistics"), deadMarkers, (startingMarkers - deadMarkers)]];
        
        if( deadMarkers  == (startingMarkers) ) {
            [self setGameOver:kGAMEOVERWON];
        }
    }
    if ( [keyPath isEqualToString:@"removeObservers"] ) {
        [object unregisterObserver:self];
    }
}

- (void)sendNextMarker:(ccTime)dt
{
    if( [rightPond count] > 0 ) {
        
        /* 
         
         random choice the marker 
         
         */
        NSUInteger randomIndex = arc4random() % [rightPond count];
        
        /* 
         
         random the location to move 
         
         */
        //NSUInteger randomY = (arc4random() % (int)( winSize.height ) );
        
        Marker *nextMarker = [rightPond objectAtIndex:randomIndex];
        [onBelt addObject:nextMarker];
        
        [rightPond removeObject:nextMarker];
        
        //CCLOG(@"nextDuck.width = %@", nextDuck.width);
        //CCLOG(@"randomY = %@", randomY);
        
        /* 
         
        set position marker will move to (cross to frames)
         
         */
//        [nextDuck runAction:
//         [CCSequence actions:
//          [CCMoveTo actionWithDuration:[self beltSpeed] position:ccp(0 - nextDuck.width, randomY )],
//          [CCCallFuncN actionWithTarget:self selector:@selector(returnDuck:)],
//          nil]
//         ];
        [nextMarker runAction:
         [CCSequence actions:
          [CCMoveTo actionWithDuration:[self beltSpeed] position: self.randomPositionOfFrames],
          [CCCallFuncN actionWithTarget:self selector:@selector(returnMarker:)],
          nil]
         ];
        [nextMarker playAnimation];
   }
}


/* set hide marker */
- (void)returnMarker:(Marker *)sender
{
    [sender stopAnimation];
    
//    CCLOG(@"returnDuck -> self.contentSize.width = %f", self.contentSize.width);
//    CCLOG(@"returnDuck -> sender.width / 2 = %f", sender.width / 2);
//    CCLOG(@"returnDuck -> sender.y = %f", sender.y);
    
    [sender setPosition:ccp( self.contentSize.width + (sender.width / 2), sender.y)];
    [onBelt removeObject:sender];
    //[rightPond addObject:sender];
}

#pragma mark Touch

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
    // pass on every touch
	return YES;
}

- (void)onEnter
{
	[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
	[super onEnter];
}

- (void)onExit
{
	[[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
	[super onExit];
}

#pragma mark Utilities

// Set the opacity of all of our children that support it
-(void) setOpacity: (GLubyte) opacity
{
    for( CCNode *node in [self children] )
    {
        if( [node conformsToProtocol:@protocol( CCRGBAProtocol)] )
        {
            [(id<CCRGBAProtocol>) node setOpacity: opacity];
        }
    }
}

/* random x for move to frames */
-(CGPoint) randomPositionOfFrames
{
    NSUInteger randomIndex = arc4random_uniform(8);
    switch (randomIndex) {
        case 0:
            return ccp(FRAME_1_X, FRAME_1_Y);
            
        case 1:
            return ccp(FRAME_2_X, FRAME_2_Y);
        
        case 2:
            return ccp(FRAME_3_X, FRAME_3_Y);
            
        case 3:
            return ccp(FRAME_4_X, FRAME_4_Y);
            
        case 4:
            return ccp(FRAME_5_X, FRAME_5_Y);
            
        case 5:
            return ccp(FRAME_6_X, FRAME_6_Y);
            
        case 6:
            return ccp(FRAME_7_X, FRAME_7_Y);
            
        case 7:
            return ccp(FRAME_8_X, FRAME_8_Y);
    }
//    if (randomIndex == 0) {
//        return 0;
//    }
//    return winSize.width;
}
//}

/* random y for move to frames */
//-(int) randomY
//{
//    NSUInteger randomIndex = arc4random_uniform(3);
//    if (randomIndex == 0) {
//        return 0;
//    } else if (randomIndex == 1) {
//        return winSize.height / 2;
//    }
//    return winSize.height;
//}
//}

@end
